
COGS = "http://latex.codecogs.com/gif.latex"


var active_control_panel = null;


function notebook(divobj)
{
    divobj.html("");
    ul = $("<ul/>");
    ul.addClass("notebook");
    for (i = 0; i < 4; ++i) {
        li = $("<li/>");
        formula(li, i, "3^" + i + "=" + 3*i);
        ul.append(li);
    }
    divobj.html(ul);
    notebook_control_panel(divobj);
}

function notebook_load(divobj, notebook_id, panel, callback)
{
    divobj.attr('notebook_id', notebook_id);
    var query_string = $.param({'notebook': notebook_id});
    divobj.ajax_load("list", query_string,
        function(text, status, xhr) {
			notebook_format(divobj, panel); 
			if (callback) callback() 
		});
}

function notebook_format(divobj, panel)
{
    var ul = divobj.find("ul");
    ul.addClass("notebook");
	var items = ul.find("li");
	if (items.length == 0)
		ul.append($("<li class='empty'>This notebook is empty.</li>"));
	items.each(function(i) {
        formula($(this), i, $(this).text());
    });
	if (panel)
		active_control_panel = notebook_control_panel(divobj, panel);
}

function notebook_control_panel(divobj, options)
{
    var div = $("<div/>");
    entry = $("<input type='text'/>");
    b = $("<input type='button'/>");
    b.attr("value", ">");
    b.click(function() 
        { notebook_add(divobj, entry.val(), multichoice_value(div));
		  entry.val(""); });
    entry.keypress(function(event) { if (event.keyCode == 13) b.click(); });
    div.append(b);
    div.append(entry);
	div.append(multichoice_small("kind", ['formula', 'constant']));
	/* control buttons */
	var bp = $("<img/>");
	bp.attr('src', "__url__/px/gui/24x24/Applications.gif");
	bp.addClass("control");
	bp.click(function() { palette(); });
	div.append(bp);
    divobj.append(div);
    if (!options || options != "nofocus")
        entry.focus();
	return div;
}

function multichoice_small(name, choices)
{
	var div = $("<div/>");
	div.addClass("multichoice-small");
	for (index in choices) {
		choice = choices[index];
		var input = $('<input type="radio"/>');
		input.attr('id', choice);
		input.attr('name', name);
		if (index == 0) input.attr('checked', 1);
		input.addClass("styled");
		var label = $('<label/>');
		label.attr('for', choice);
		label.text(choice);
		div.append(input);
		div.append(label);
		div.append("<br/>");
	}
	div.each(function() { Custom.init(this); });
	return div;
}

function multichoice_value(divobj)
{
	return divobj.find(".multichoice-small").find(":radio").val() 
				? "formula" : "constant";
}

function notebook_add(divobj, latex, kind)
{
    var ul = divobj.find(".notebook");
	ul.find(".empty").remove();
    var length = ul.find("li").length;
    var li = $("<li/>");
	li.attr('kind', kind);
	li.attr('entry', latex);
    formula(li, length, latex);
    ul.append(li);
    notify();
    ajax_add_formula(li, latex, kind);
}

function formula(divobj, index, latex)
{
    divobj.html("");
    var idx = $("<a/>");
    idx.addClass("index");
    idx.text("["+index+"]");
    var img = $("<img/>");
	img.attr("entry", divobj.attr("entry"));
    img.addClass("latex");
    img.attr("alt", latex);
    load_image(img, COGS + "?" + latex);
    img.click(function() { formula_edit(img); });
    divobj.append(idx);
    divobj.append(img);
	/* plot */
	if (latex.match("^y=")) {
		var a = $('<a/>');
		a.text("plot");
		a.click(function() { formula_plot(divobj, latex.substring(2)); });
		a.addClass("op-small");
		divobj.append(a);
	}
}

function formula_plot(divobj, expression)
{
	var plot = $("<div/>");
	plot.attr("title", "Plot");
	plot.html(img_pending());
	//divobj.dialog({ position: 'top' });
	plot.insertAfter(divobj);
	notify();
	setTimeout(function() {
		plot.ajax_load("plot", $.param({f: expression}), function() {
			var img = plot.find("img");
			if (img.length > 0) {
				plot.html(img);
				notify();
				img.load(notify);
				img.click(function() { plot.remove(); notify(); });
			}
			else formula_plot(divobj, expression); /* retry */
		});
	}, 50);
}

function formula_edit(img)
{
    var edit = $("<input type='text'/>");
    edit.val(img.attr('entry'));
    edit.keypress(function(event) { 
        if (event.keyCode == 13) {
            var latex = edit.val();
            edit.remove();
            ajax_update_formula(img.closest("li"), latex);
            if (latex != "") {
				img.attr('entry', latex);
				formula_render(img, latex);
            }
            else {
                img.closest("li").remove();
            }
        }
    });
    edit.blur(function() {
        edit.remove();
        img.removeClass('hidden');
    });
    img.addClass('hidden');
    img.after(edit);
    edit.focus();
}

function formula_render(img, latex)
{
	img.removeClass('hidden');
	img.attr('alt', latex);
	load_image(img, COGS + "?" + latex);
}

function ajax_add_formula(li, latex, kind)
{
    var idx = li.find(".index");
    var idx_text = idx.text();
    var notebook_id = li.closest("[notebook_id]").attr("notebook_id");
    idx.html(img_synchronizing());
    $.ajax_post("sign1", {'content': latex, 'notebook': notebook_id, 
	                      'kind': kind},
    function(data, status) { 
        idx.text(idx_text);
        li.attr('key', data);
		ack();
    });
}

function ajax_update_formula(li, latex)
{
    var idx = li.find(".index");
    var idx_text = idx.text();
    var key = li.attr("key");
	var kind = li.attr("kind");
    idx.html(img_synchronizing());
    $.ajax_post("update", {'content': latex, 'kind': kind, 'key': key},
    function(data, status) {
        idx.text(idx_text);
		formula_render(li.find("img"), data);
		ack();
    });
}

function palette(notebook_id)
{
	$('#palette').dialog("open");
	var inside = $('#favorites');
	inside.html(img_pending());
	if (notebook_id == null) notebook_id = user() + ":Favorites";
	notebook_load(inside, notebook_id, false, function() {
		inside.find("li[entry]").each(
			function() { palette_button($(this)); });
	});
	load_research_palette();
}

function load_research_palette()
{
	$('#research').ajax_load("notebooks", "", function() {
		$('#research').find("li").each(function() {
			if ($(this).text().match("wiki:.*") != null) {
				var notebook_a = $(this).text();
				var a = $("<a/>");
				a.text(notebook_a);
				a.click(function() {
					notebook_load($('#research'), notebook_a, false,
					function() {
						$('#research').find("li[entry]").each(
							function() { palette_button($(this)); });
						var back_a = $("<a>back to list</a>");
						back_a.click(load_research_palette);
						back_a.addClass("op-small");
						$('#research').append(back_a);
					});
				});
				$(this).html(a);
			}
			else $(this).remove();
		});
	});
}

function palette_button(li)
{
	var plus = $("<img/>");
	plus.attr('src', "__url__/px/gui/24x24/Plus.gif");
	plus.addClass("control");
	plus.click(function() {
		active_control_panel.find("[type=text]").val(li.attr('entry'));
		active_control_panel.find("[type=button]").click();
	});
	li.prepend(plus);
	li.find(".index").remove();
}

function load_image(img, uri)
{
    img.attr("src", "__url__/px/gui/16x16/ajax-loader.gif");
    img.load(function() { img.unbind('load'); 
        img.load(notify); img.attr('src', uri); 
    });
}

function img_pending()
{
    var img = $("<img/>");
    img.attr('src', "__url__/px/gui/16x16/ajax-loader.gif");
    return img;
}

function img_synchronizing()
{
    var img = $("<img/>");
    img.attr('src', "__url__/px/gui/16x16/ajax-sync.gif");
    return img;
}
